import { defineStore } from 'pinia'
import { getStorage, setStorage } from '@/utils/db'
import { gameUtil } from '@/utils/game-util'
export const useGameStore = defineStore('game', {
  state: () => ({
    // 游戏配置
    DIFFICULTY_CONFIG: {
      easy: { gridSize: 6, baseColors: 3, colorIncrement: 1, baseStepsMultiplier: 1.8, baseScore: 100 },
      medium: { gridSize: 8, baseColors: 5, colorIncrement: 1, baseStepsMultiplier: 1.5, baseScore: 200 },
      hard: { gridSize: 10, baseColors: 7, colorIncrement: 1, baseStepsMultiplier: 1.2, baseScore: 300 }
    },
    COLORS: [
      { code: '#FF5252', name: '红色' },
      { code: '#4CAF50', name: '绿色' },
      { code: '#2196F3', name: '蓝色' },
      { code: '#FFC107', name: '黄色' },
      { code: '#9C27B0', name: '紫色' },
      { code: '#FF9800', name: '橙色' },
      { code: '#795548', name: '棕色' },
      { code: '#607D8B', name: '灰色' },
      { code: '#E84393', name: '粉色' },
      { code: '#16A085', name: '青绿色' }
    ],
    REWARDS: [
      { id: 'theme1', name: '霓虹主题', description: '解锁霓虹色彩主题', score: 500, icon: 'lightbulb-o' },
      { id: 'hint5', name: '提示包×5', description: '获得5次免费提示机会', score: 300, icon: 'question-circle' },
      { id: 'theme2', name: '复古主题', description: '解锁复古色彩主题', score: 800, icon: 'paint-brush' },
      { id: 'level_skip', name: '关卡跳过', description: '可跳过一个关卡', score: 1000, icon: 'forward' },
      { id: 'theme3', name: '暗黑主题', description: '解锁暗黑色彩主题', score: 1200, icon: 'moon-o' },
      { id: 'double_score', name: '双倍积分卡', description: '一局游戏获得双倍积分', score: 1500, icon: 'star' }
    ],
    
    // 游戏状态
    grid: [],
    originalGrid: [],
    selectedCell: { x: 0, y: 0 },
    currentColor: '',
    targetColor: '',
    stepsUsed: 0,
    maxSteps: 10,
    optimalSteps: 0,
    currentLevel: 1,
    currentDifficulty: 'easy',
    unlockedLevels: { easy: 1, medium: 1, hard: 1 },
    gameCompleted: false,
    soundEnabled: true,
    hintsUsed: 0,
    isAnimating: false,
    totalScore: 0,
    levelScores: {},
    currentStreak: 0,
    maxStreak: 0,
    unlockedRewards: [],
    hintsRemaining: 10,
    
    // 界面状态
    currentScreen: 'difficulty' // difficulty, level, game
  }),
  
  getters: {
    // 获取当前关卡配置
    currentLevelConfig(state) {
      const config = state.DIFFICULTY_CONFIG[state.currentDifficulty]
      const colorCount = Math.min(
        config.baseColors + Math.floor((state.currentLevel - 1) / 3) * config.colorIncrement,
        state.COLORS.length
      )
      
      return {
        ...config,
        colorCount,
        maxSteps: Math.round(config.gridSize * colorCount * config.baseStepsMultiplier),
        optimalSteps: Math.round(config.gridSize * colorCount * config.baseStepsMultiplier * (0.6 + Math.random() * 0.1)),
        complexity: Math.min(1, 0.3 + (state.currentLevel * 0.05))
      }
    },
    
    // 获取当前进度百分比
    progressPercentage(state) {
      const config = state.DIFFICULTY_CONFIG[state.currentDifficulty]
      const totalCells = config.gridSize * config.gridSize
      let completedCells = 0
      
      for (let y = 0; y < config.gridSize; y++) {
        for (let x = 0; x < config.gridSize; x++) {
          if (state.grid[y] && state.grid[y][x] === state.targetColor) {
            completedCells++
          }
        }
      }
      
      return Math.round((completedCells / totalCells) * 100)
    }
  },
  
  actions: {
    // 初始化游戏状态
    initGameState() {
      const savedState = getStorage('gameState')
      if (savedState) {
        Object.assign(this, savedState)
      }
    },
    
    // 保存游戏状态
    saveGameState() {
      // 排除临时状态
      const stateToSave = { ...this }
      delete stateToSave.grid
      delete stateToSave.originalGrid
      delete stateToSave.gameCompleted
      delete stateToSave.isAnimating
      
      setStorage('gameState', stateToSave)
    },
    
    // 初始化关卡
    initLevel() {
      const levelConfig = this.currentLevelConfig
      this.maxSteps = levelConfig.maxSteps
      this.optimalSteps = levelConfig.optimalSteps
      
      // 生成网格
      this.originalGrid = this.generateLevelGrid(this.currentLevel, this.currentDifficulty)
      this.grid = JSON.parse(JSON.stringify(this.originalGrid))
      
      // 重置状态
      this.selectedCell = { x: 0, y: 0 }
      this.currentColor = this.grid[0][0]
      this.stepsUsed = 0
      this.gameCompleted = false
      this.hintsUsed = 0
      this.isAnimating = false
      
      // 设置目标颜色
      let targetColorIndex
      do {
        targetColorIndex = Math.floor(Math.random() * levelConfig.colorCount)
      } while (this.COLORS[targetColorIndex].code === this.currentColor)
      
      this.targetColor = this.COLORS[targetColorIndex].code
    },
    
    // 生成关卡网格
    generateLevelGrid(level, difficulty) {
		console.log(level, difficulty);
      const config = this.DIFFICULTY_CONFIG[difficulty]
      const levelConfig = this.currentLevelConfig
      const grid = []
      
      // 使用种子随机数生成一致的网格
      const seed = level * 1000 + difficulty.charCodeAt(0)
      const rand = gameUtil.mulberry32(seed)
      
      for (let y = 0; y < config.gridSize; y++) {
        const row = []
        for (let x = 0; x < config.gridSize; x++) {
          if (x > 0 && rand() < (1 - levelConfig.complexity) * 0.7) {
            row.push(row[x - 1])
          } else if (y > 0 && rand() < (1 - levelConfig.complexity) * 0.7) {
            row.push(grid[y - 1][x])
          } else {
            const colorIndex = Math.floor(rand() * levelConfig.colorCount)
            row.push(this.COLORS[colorIndex].code)
          }
        }
        grid.push(row)
      }
      
      return this.optimizeGridForSolution(grid, config.gridSize, levelConfig.colorCount)
    },
    
    // 优化网格确保有解
    optimizeGridForSolution(grid, gridSize, colorCount) {
      const optimizedGrid = JSON.parse(JSON.stringify(grid))
      const startColor = optimizedGrid[0][0]
      const visited = Array(gridSize).fill().map(() => Array(gridSize).fill(false))
      const regions = []
      
      // 找到所有连通区域
      for (let y = 0; y < gridSize; y++) {
        for (let x = 0; x < gridSize; x++) {
          if (!visited[y][x]) {
            const color = optimizedGrid[y][x]
            const region = this.findConnectedRegion(optimizedGrid, x, y, color, visited, gridSize)
            regions.push({ color, cells: region, size: region.length })
          }
        }
      }
      
      // 扩展起始区域
      const startRegions = regions.filter(r => r.color === startColor)
      if (startRegions.length > 0) {
        startRegions.sort((a, b) => b.size - a.size)
        if (startRegions[0].size < gridSize) {
          this.expandRegion(
            optimizedGrid, 
            startRegions[0].cells[0].x, 
            startRegions[0].cells[0].y, 
            startColor, 
            gridSize, 
            gridSize * 0.3
          )
        }
      }
      
      return optimizedGrid
    },
    
    // 查找连通区域
    findConnectedRegion(grid, x, y, color, visited, gridSize) {
      if (x < 0 || x >= gridSize || y < 0 || y >= gridSize || visited[y][x] || grid[y][x] !== color) {
        return []
      }
      
      visited[y][x] = true
      const region = [{ x, y }]
      
      // 检查四个方向
      region.push(...this.findConnectedRegion(grid, x + 1, y, color, visited, gridSize))
      region.push(...this.findConnectedRegion(grid, x - 1, y, color, visited, gridSize))
      region.push(...this.findConnectedRegion(grid, x, y + 1, color, visited, gridSize))
      region.push(...this.findConnectedRegion(grid, x, y - 1, color, visited, gridSize))
      
      return region
    },
    
    // 扩展区域
    expandRegion(grid, x, y, color, gridSize, targetSize) {
      const queue = [{ x, y }]
      const visited = Array(gridSize).fill().map(() => Array(gridSize).fill(false))
      visited[y][x] = true
      
      let expandedCount = 0
      
      while (queue.length > 0 && expandedCount < targetSize) {
        const { x, y } = queue.shift()
        const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
        
        for (const [dx, dy] of directions) {
          const nx = x + dx
          const ny = y + dy
          
          if (nx >= 0 && nx < gridSize && ny >= 0 && ny < gridSize && !visited[ny][nx]) {
            visited[ny][nx] = true
            grid[ny][nx] = color
            expandedCount++
            queue.push({ x: nx, y: ny })
            
            if (expandedCount >= targetSize) break
          }
        }
      }
    },
    
    // 填充颜色
    async fillColor(newColor) {
      if (this.stepsUsed >= this.maxSteps || this.isAnimating || newColor === this.currentColor) {
        return
      }
      
      this.isAnimating = true
      this.stepsUsed++
      
      const { x, y } = this.selectedCell
      const originalColor = this.currentColor
      
      // 执行填充动画
      await this.animateFloodFill(x, y, originalColor, newColor)
      
      // 更新状态
      this.currentColor = newColor
      this.isAnimating = false
      
      // 检查游戏状态
      this.checkGameStatus()
    },
    
    // 动画填充
    animateFloodFill(startX, startY, targetColor, newColor) {
      return new Promise((resolve) => {
        const config = this.DIFFICULTY_CONFIG[this.currentDifficulty]
        const queue = [[startX, startY]]
        const visited = Array(config.gridSize).fill().map(() => Array(config.gridSize).fill(false))
        visited[startY][startX] = true
        
        // 处理填充队列
        const processQueue = () => {
          if (queue.length === 0) {
            resolve()
            return
          }
          
          const levelSize = queue.length
          let processed = 0
          
          for (let i = 0; i < levelSize; i++) {
            setTimeout(() => {
              const [x, y] = queue.shift()
              
              // 更新颜色
              this.grid[y][x] = newColor
              
              // 检查四个方向
              const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
              directions.forEach(([dx, dy]) => {
                const nx = x + dx
                const ny = y + dy
                
                if (nx >= 0 && nx < config.gridSize && ny >= 0 && ny < config.gridSize && 
                    !visited[ny][nx] && this.grid[ny][nx] === targetColor) {
                  visited[ny][nx] = true
                  queue.push([nx, ny])
                }
              })
              
              processed++
              if (processed === levelSize) {
                setTimeout(processQueue, 30)
              }
            }, i * 15)
          }
        }
        
        processQueue()
      })
    },
    
    // 检查游戏状态
    checkGameStatus() {
      const config = this.DIFFICULTY_CONFIG[this.currentDifficulty]
      const totalCells = config.gridSize * config.gridSize
      let completedCells = 0
      
      for (let y = 0; y < config.gridSize; y++) {
        for (let x = 0; x < config.gridSize; x++) {
          if (this.grid[y][x] === this.targetColor) {
            completedCells++
          }
        }
      }
      
      // 游戏胜利
      if (completedCells === totalCells) {
        this.gameCompleted = true
        this.calculateAndSaveScore()
        this.unlockNextLevel()
        return true
      }
      
      // 游戏失败
      if (this.stepsUsed >= this.maxSteps) {
        this.gameCompleted = true
        this.currentStreak = 0
        this.saveGameState()
        return false
      }
      
      return null
    },
    
    // 计算并保存分数
    calculateAndSaveScore() {
      const config = this.DIFFICULTY_CONFIG[this.currentDifficulty]
      
      // 计算积分
      const stepMultiplier = Math.min(1.5, this.optimalSteps / this.stepsUsed)
      const hintPenalty = Math.max(0.5, 1 - (this.hintsUsed * 0.1))
      const streakBonus = 1 + Math.min(0.5, this.currentStreak * 0.05)
      const score = Math.round(config.baseScore * stepMultiplier * hintPenalty * streakBonus)
      
      // 更新状态
      this.totalScore += score
      this.currentStreak++
      this.maxStreak = Math.max(this.maxStreak, this.currentStreak)
      
      // 记录关卡最高分
      const levelKey = `${this.currentDifficulty}_${this.currentLevel}`
      if (!this.levelScores[levelKey] || score > this.levelScores[levelKey]) {
        this.levelScores[levelKey] = score
      }
      
      this.saveGameState()
      return score
    },
    
    // 解锁下一关
    unlockNextLevel() {
      const currentUnlocked = this.unlockedLevels[this.currentDifficulty] || 1
      
      if (this.currentLevel < 15 && this.currentLevel >= currentUnlocked) {
        this.unlockedLevels[this.currentDifficulty] = currentUnlocked + 1
        this.saveGameState()
      }
    },
    
    // 显示提示
    showHint() {
      if (this.gameCompleted || this.isAnimating || this.hintsRemaining <= 0) {
        return
      }
      
      this.hintsUsed++
      this.hintsRemaining--
      this.saveGameState()
      
      const config = this.DIFFICULTY_CONFIG[this.currentDifficulty]
      const currentColor = this.currentColor
      const { x, y } = this.selectedCell
      const visited = Array(config.gridSize).fill().map(() => Array(config.gridSize).fill(false))
      const edgeCells = []
      
      // 找到边缘单元格
      this.findEdges(x, y, currentColor, visited, config.gridSize, edgeCells)
      
      // 计算最佳颜色
      const colorCounts = {}
      edgeCells.forEach(cell => {
        const color = this.grid[cell.y][cell.x]
        if (color !== currentColor && !colorCounts[color]) {
          const countVisited = Array(config.gridSize).fill().map(() => Array(config.gridSize).fill(false))
          colorCounts[color] = this.countFloodFill(cell.x, cell.y, color, countVisited, config.gridSize)
        }
      })
      
      // 返回最佳颜色
      let bestColor = null
      let maxCount = 0
      for (const color in colorCounts) {
        if (colorCounts[color] > maxCount) {
          maxCount = colorCounts[color]
          bestColor = color
        }
      }
      
      return bestColor
    },
    
    // 查找边缘
    findEdges(x, y, color, visited, gridSize, edgeCells) {
      if (x < 0 || x >= gridSize || y < 0 || y >= gridSize || visited[y][x] || this.grid[y][x] !== color) {
        return
      }
      
      visited[y][x] = true
      const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
      
      directions.forEach(([dx, dy]) => {
        const nx = x + dx
        const ny = y + dy
        
        if (nx >= 0 && nx < gridSize && ny >= 0 && ny < gridSize) {
          if (this.grid[ny][nx] !== color) {
            edgeCells.push({x: nx, y: ny})
          } else if (!visited[ny][nx]) {
            this.findEdges(nx, ny, color, visited, gridSize, edgeCells)
          }
        }
      })
    },
    
    // 计算填充数量
    countFloodFill(x, y, targetColor, visited, gridSize) {
      if (x < 0 || x >= gridSize || y < 0 || y >= gridSize || visited[y][x] || this.grid[y][x] !== targetColor) {
        return 0
      }
      
      visited[y][x] = true
      let count = 1
      
      count += this.countFloodFill(x + 1, y, targetColor, visited, gridSize)
      count += this.countFloodFill(x - 1, y, targetColor, visited, gridSize)
      count += this.countFloodFill(x, y + 1, targetColor, visited, gridSize)
      count += this.countFloodFill(x, y - 1, targetColor, visited, gridSize)
      
      return count
    },
    
    // 兑换奖励
    redeemReward(rewardId) {
      const reward = this.REWARDS.find(r => r.id === rewardId)
      if (!reward) return false
      
      if (this.unlockedRewards.includes(rewardId) || this.totalScore < reward.score) {
        return false
      }
      
      this.totalScore -= reward.score
      this.unlockedRewards.push(rewardId)
      this.saveGameState()
      return true
    }
  }
})